package com.fmyexample.mcsecurityboot.config.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fmyexample.mcsecurityboot.modular.model.User;
import com.fmyexample.mcsecurityboot.modular.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName UserDetailsServiceImpl
 * @Description TODO Security自带UserDetailsService接口实现
 * @createTime 2020/4/15 11:23
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User one = userService.getOne(Wrappers.<User>query().eq(User.USER_PHONE, s));
        if (one == null) {
            //这里抛出啥异常都不行，到最后还是会变成 BadCredentialsException 异常，所以无所谓
            throw new UsernameNotFoundException("用户名不存在");
        }
        CuUserDetails cuUserDetails = new CuUserDetails();
        BeanUtils.copyProperties(one, cuUserDetails);
        SecurityConfig.SALT_HOLDER.set(cuUserDetails.getUserSalt());
        return cuUserDetails;
    }
}
